
Object.defineProperty(exports, "__esModule", { value: true });
/**
* @module index
* @author: Hjava
* @description: IM模块
* @since: 2018-07-22 14:55:06
*/
var http_core_1 = __webpack_require__(/*! _http/http.core */ "./src/core/http/http.core.ts");
var im_constant_1 = __webpack_require__(/*! _im/im.constant */ "./src/core/im/im.constant.ts");
var im_message_1 = __webpack_require__(/*! _im/im.message */ "./src/core/im/im.message.ts");
var im_session_1 = __webpack_require__(/*! _im/im.session */ "./src/core/im/im.session.ts");
var analytics_1 = __webpack_require__(/*! _util/analytics */ "./src/core/utils/analytics.ts");
var constant_1 = __webpack_require__(/*! _util/constant */ "./src/core/utils/constant.ts");
var eventEmitter_1 = __webpack_require__(/*! _util/eventEmitter */ "./src/core/utils/eventEmitter.ts");
var timer_1 = __webpack_require__(/*! _util/timer */ "./src/core/utils/timer.ts");
var userData_1 = __webpack_require__(/*! _util/userData */ "./src/core/utils/userData.ts");
var owlController_1 = __webpack_require__(/*! _util/owlController */ "./src/core/utils/owlController.ts");
var log_1 = __webpack_require__(/*! ./../utils/log */ "./src/core/utils/log.ts");
var ACK = [
    [im_session_1.default.IMAckMsgs, im_session_1.default.IMAckSyncMsgs],
    [im_session_1.default.IMAckGroupMsgs, im_session_1.default.IMAckSyncGroupMsgs]
];
var newIMAck = function (message, uid) {
    return new ACK[1 & ([im_constant_1.default.IM.URI_IM_SEND_GROUP_MSG, im_constant_1.default.IM.URI_IM_CANCEL_GROUP_MSG].indexOf(message.uri) !== -1)][1 & (message.fromUid === uid)]({
        uid: uid,
        msgIds: [message['msgId']]
    });
};
var IMSDK = /** @class */ (function () {
    function IMSDK(loginSDK) {
        var _this = this;
        this._loginSDK = null;
        this._msgMap = {};
        this._timeMap = {};
        this._sendMessageTimeoutMap = {};
        this._readTimeMap = {};
        this._MAX_ACK_TIME = 15 * 1000;
        this.constant = im_constant_1.default;
        this._loginSDK = loginSDK;
        eventEmitter_1.default.on(im_constant_1.default.IM.URI_IM_SEND_MSG, this._onMessage.bind(this));
        eventEmitter_1.default.on(im_constant_1.default.IM.URI_IM_SEND_MSG2, this._onMessage.bind(this));
        eventEmitter_1.default.on(im_constant_1.default.IM.URI_IM_SEND_GROUP_MSG, this._onMessage.bind(this));
        eventEmitter_1.default.on(im_constant_1.default.IM.URI_IM_CANCEL_MSG, this._onMessage.bind(this));
        eventEmitter_1.default.on(im_constant_1.default.IM.URI_IM_CANCEL_MSG2, this._onMessage.bind(this));
        eventEmitter_1.default.on(im_constant_1.default.IM.URI_IM_CANCEL_GROUP_MSG, this._onMessage.bind(this));
        eventEmitter_1.default.on(im_constant_1.default.IM.URI_IM_MARK_READ, this._onNotice.bind(this));
        eventEmitter_1.default.on(im_constant_1.default.IM.URI_IM_MARK_READS, this._onNotice.bind(this));
        eventEmitter_1.default.on(im_constant_1.default.IM.URI_IM_GROUP_NOTICE, this._onNotice.bind(this));
        eventEmitter_1.default.on(im_constant_1.default.IM.URI_IM_CHAT_NOTICE, this._onNotice.bind(this));
        eventEmitter_1.default.on(im_constant_1.default.IM.URI_IM_SEND_MSG_RES, this._onACK.bind(this));
        eventEmitter_1.default.on(im_constant_1.default.IM.URI_IM_SEND_GROUP_MSG_RES, this._onACK.bind(this));
        eventEmitter_1.default.on(im_constant_1.default.IM.URI_IM_CANCEL_MSG_RES, this._onACK.bind(this));
        eventEmitter_1.default.on(im_constant_1.default.IM.URI_IM_CANCEL_GROUP_MSG_RES, this._onACK.bind(this));
        eventEmitter_1.default.on(im_constant_1.default.IM.URI_IM_SYNC_READ, this._onRead.bind(this));
        eventEmitter_1.default.on(im_constant_1.default.IM.URI_IM_SYNC_READ2, this._onRead.bind(this));
        eventEmitter_1.default.on(im_constant_1.default.IM.URI_IM_SYNC_READ_RES, this._onReadACK.bind(this));
        eventEmitter_1.default.on(im_constant_1.default.IM.URI_IM_RECEIPT_MSG_RES, this._onReciept.bind(this));
        eventEmitter_1.default.on(im_constant_1.default.IM.URI_IM_RECEIPT_GROUP_MSG_RES, this._onReciept.bind(this));
        eventEmitter_1.default.on(im_constant_1.default.IM.URI_IM_OPPOSITE_SYNC2_READ, this._onOppsiteRead.bind(this));
        eventEmitter_1.default.on(im_constant_1.default.IM.URI_IM_OPPOSITE_SYNC2_READ2, this._onOppsiteRead.bind(this));
        eventEmitter_1.default.on(im_constant_1.default.IM.URI_IM_OPPOSITE_SYNC2_READ_RES, this._onOppositeReadAck.bind(this));
        eventEmitter_1.default.on(im_constant_1.default.IM.URI_IM_RECEIPT_GROUP_MSGS_RECV, this._onReceiptGroupMessage.bind(this));
        eventEmitter_1.default.on(im_constant_1.default.IM.URI_IM_RECEIPT_GROUP_MSGS_RES, this._onReceiptGroupMessageAck.bind(this));
        eventEmitter_1.default.on(im_constant_1.default.IM.URI_IM_PERSON_ADDITION_MSG2, this._onMessageAddition.bind(this));
        eventEmitter_1.default.on(im_constant_1.default.IM.URI_IM_GROUP_ADDITION_MSG2, this._onMessageAddition.bind(this));
        /**
         * batch ack 单聊、群聊的离线接口会触发这个，不过目前离线接口已经不再使用了
         */
        eventEmitter_1.default.on('__IMAck', function (msgs) {
            var AA = [
                [
                    [],
                    []
                ],
                [
                    [],
                    []
                ]
            ];
            var i;
            for (i = 0; i < msgs.length; i++) {
                AA[1 & ([im_constant_1.default.IM.URI_IM_SEND_GROUP_MSG, im_constant_1.default.IM.URI_IM_CANCEL_GROUP_MSG].indexOf(msgs[i].uri) !== -1)][1 & (msgs[i].fromUid === _this._loginSDK.getUID())].push(msgs[i].msgId);
            }
            var Id = 0;
            for (i = 0; i < 2; i++) {
                for (var j = 0; j < 2; j++) {
                    while ((Id = AA[i][j].splice(0, 1500)).length) {
                        _this.send(new ACK[i][j]({
                            uid: _this._loginSDK.getUID(),
                            msgIds: Id
                        }));
                    }
                }
            }
        });
        /*
        感觉是废弃了，没有找到发送通知的地方
        */
        eventEmitter_1.default.on('chatAcks', function (mids) {
            if (mids.length > 0) {
                _this.send(new im_session_1.default.IMAckMsgs({
                    uid: _this._loginSDK.getUID(),
                    msgIds: mids
                }));
            }
        });
        /*
        感觉是废弃了，没有找到发送通知的地方
        */
        eventEmitter_1.default.on('groupAcks', function (mids) {
            if (mids.length > 0) {
                _this.send(new im_session_1.default.IMAckGroupMsgs({
                    uid: _this._loginSDK.getUID(),
                    msgIds: mids
                }));
            }
        });
    }
    IMSDK.prototype.clearMsgMap = function (uuid) {
        var item = this._msgMap[uuid];
        if (!item || !item.time) {
            return;
        }
        this.sendStatisticalData(item);
        if (item.timer) {
            clearTimeout(this._msgMap[uuid].timer);
            this._msgMap[uuid].timer = null;
        }
        this._msgMap[uuid] = null;
        delete this._msgMap[uuid];
    };
    IMSDK.prototype.clearTimemoutMsg = function () {
        var now = timer_1.default.get();
        for (var i in this._msgMap) {
            var item = this._msgMap[i];
            if (item && now - item.time > this._MAX_ACK_TIME) {
                this.clearMsgMap(i);
            }
        }
    };
    IMSDK.prototype.sendStatisticalData = function (item) {
        var time = timer_1.default.get() - item.time;
        if (time > this._MAX_ACK_TIME) {
            time = this._MAX_ACK_TIME;
        }
        var Owl = userData_1.default.get('Owl');
        if (Owl) {
            Owl.addApi({
                name: 'sendMessageTime',
                responseTime: time
            });
        }
    };
    IMSDK.prototype.send = function (message) {
        var _this = this;
        try {
            if (message && [
                im_constant_1.default.IM.URI_IM_SEND_GROUP_MSG,
                im_constant_1.default.IM.URI_IM_SEND_MSG,
                im_constant_1.default.IM.URI_IM_SEND_MSG2,
                im_constant_1.default.IM.URI_IM_CANCEL_MSG,
                im_constant_1.default.IM.URI_IM_CANCEL_MSG2,
                im_constant_1.default.IM.URI_IM_CANCEL_GROUP_MSG,
                im_constant_1.default.IM.URI_IM_RECEIPT_MSG_REQ,
                im_constant_1.default.IM.URI_IM_RECEIPT_GROUP_MSG_REQ
            ].indexOf(message.uri) !== -1) {
                this._msgMap[message.msgUuid] = {
                    time: timer_1.default.get(),
                    timer: 0
                };
                this._msgMap[message.msgUuid].timer = setTimeout(function () {
                    //15s后进行检测，15s是因为上层也是15s做了重发的操作
                    //这里需要做一个批量最多10个检测
                    var uuids = [];
                    var maxLength = 10;
                    var i = 0;
                    for (var uuid in _this._msgMap) {
                        if (_this._msgMap[uuid]) {
                            i++;
                            if (i >= maxLength) {
                                break;
                            }
                            uuids.push(uuid);
                        }
                    }
                    log_1.default.log('IMSDK::send im message timeout check info:' + uuids);
                    if (uuids.length) {
                        http_core_1.default.request('/msg/api/chat/v3/message/exist', {
                            data: {
                                u: _this._loginSDK.getUID(),
                                ai: _this._loginSDK.getAppId(),
                                svid: im_constant_1.default.SVID_IM,
                                msguuid: uuids
                            },
                            success: function (result) {
                                if (result && result.rescode === 0 && result.data) {
                                    for (var i = 0, len = result.data.length; i < len; i++) {
                                        var msg = result.data[i];
                                        var ackObject = {
                                            rescode: 0,
                                            seqId: msg.seqid,
                                            msgId: msg.msgid,
                                            clusterId: msg.clusterid,
                                            msgUuid: msg.msguuid,
                                            deviceType: msg.devicetype
                                        };
                                        log_1.default.log('IMSDK::send im message timeout check success info:' + JSON.stringify(ackObject));
                                        eventEmitter_1.default.emit('ack', ackObject);
                                        _this.clearMsgMap(msg.msguuid);
                                    }
                                }
                            }
                        });
                    }
                }, this._MAX_ACK_TIME);
            }
            this._loginSDK._sendTransUp(im_constant_1.default.SVID_IM, message);
            if (message.uri === im_constant_1.default.IM.URI_IM_SEND_MSG
                || message.uri === im_constant_1.default.IM.URI_IM_SEND_MSG2
                || message.uri === im_constant_1.default.IM.URI_IM_SEND_GROUP_MSG
                || message.uri === im_constant_1.default.IM.URI_IM_CANCEL_MSG
                || message.uri === im_constant_1.default.IM.URI_IM_CANCEL_MSG2
                || message.uri === im_constant_1.default.IM.URI_IM_CANCEL_GROUP_MSG) {
                var valObject = {
                    id: message.msgUuid,
                    chat: message.toUid ? message.toUid : (message.toGuid ? message.toGuid : void 0),
                    messageType: message.type ? message.type : 0,
                    sessionType: (message.uri === im_constant_1.default.IM.URI_IM_SEND_MSG ||
                        message.uri === im_constant_1.default.IM.URI_IM_SEND_MSG2 ||
                        message.uri === im_constant_1.default.IM.URI_IM_CANCEL_MSG ||
                        message.uri === im_constant_1.default.IM.URI_IM_CANCEL_MSG2) ? 'chat' : 'groupchat'
                };
                // Log.log('IMSDK::send im message info:' + JSON.stringify(valObject))
                analytics_1.default.report({
                    nm: 'message_send_start',
                    val: valObject
                });
                if (message.msgUuid && !this._timeMap[message.msgUuid]) {
                    this._timeMap[message.msgUuid] = Date.now();
                    this._sendMessageTimeoutMap[message.msgUuid] = setTimeout(function () {
                        owlController_1.default.send({
                            name: 'message_send_finished',
                            value: 0,
                            tag: {
                                status: 0
                            }
                        });
                    }, 15 * 1000);
                }
            }
            if (message.uri === im_constant_1.default.IM.URI_IM_SYNC_READ || message.uri === im_constant_1.default.IM.URI_IM_SYNC_READ2) {
                var web_read_object = JSON.stringify(message.syncReadItems.map(function (item) {
                    return {
                        id: item.chatId,
                        cts: item.stamp,
                        sts: item.sts
                    };
                }));
                // Log.log('IMSDK::send im send read sync info:' + web_read_object + ' uuid:' + message.msgUuid)
                analytics_1.default.report({
                    nm: 'read_im_send',
                    val: {
                        uuid: message.msgUuid,
                        'web_read': web_read_object
                    }
                });
                if (message.msgUuid && !this._readTimeMap[message.msgUuid]) {
                    this._readTimeMap[message.msgUuid] = Date.now();
                }
            }
        }
        catch (e) {
            log_1.default.error(e);
        }
    };
    /**
     * @param message {!Message}
     */
    IMSDK.prototype._onMessage = function (message) {
        try {
            this.send(this._ack(message));
            // let valObject = {
            //     id: message.msgUuid,
            //     mid: typeof message.msgId === 'string' ? message.msgId : message.msgId.toString(),
            //     chat: message.toUid ? (userData.get('uid') === message.toUid ? message.fromUid : message.toGuid) : (message.toGuid ? message.toGuid : void 0),
            //     messageType: message.type ? message.type : 0
            // }
            // Log.log('IMSDK::_onMessage im receive online message info:' + JSON.stringify(valObject))
            // logManager.report({
            //     nm: 'message_receive_success',
            //     val: valObject
            // });
            // 收消息不上报owl了，owl调用一次发一次请求，大量收消息的话会导致问题
            // owlController.send({
            //     name: 'message_receive_success',
            //     value: 0
            // });
        }
        catch (e) {
            log_1.default.error(e);
        }
        eventEmitter_1.default.emit(constant_1.MESSAGE_EVENT.MESSAGE, message);
        eventEmitter_1.default.emit(constant_1.MESSAGE_EVENT.IM_MESSAGE, message);
    };
    IMSDK.prototype._ack = function (message) {
        return newIMAck(message, this._loginSDK.getUID());
    };
    /**
     * @param message {!Message} 发送消息结果
     */
    IMSDK.prototype._onACK = function (message) {
        if (message) {
            this.clearMsgMap(message.msgUuid);
        }
        if (message.rescode === 0 && this._timeMap[message.msgUuid]) {
            var valObject = {
                id: message.msgUuid,
                mid: message.msgId,
                time: Date.now() - this._timeMap[message.msgUuid]
            };
            // Log.log('IMSDK::send im message success info:' + JSON.stringify(valObject))
            analytics_1.default.report({
                nm: 'message_send_success',
                val: valObject
            });
            owlController_1.default.send({
                name: 'message_send_finished',
                value: Date.now() - this._timeMap[message.msgUuid],
                tag: {
                    status: 1
                }
            });
            clearTimeout(this._sendMessageTimeoutMap[message.msgUuid]);
            delete this._sendMessageTimeoutMap[message.msgUuid];
        }
        else {
            var valObject = {
                code: message.rescode,
                id: message.msgUuid
            };
            // Log.log('IMSDK::send im message fail info:' + JSON.stringify(valObject))
            analytics_1.default.report({
                nm: 'message_send_error',
                val: valObject
            });
        }
        // 重置
        this._timeMap[message.msgUuid] = void 0;
        eventEmitter_1.default.emit('ack', message);
    };
    /**
     * @param message {!Message} 收到已读同步
     */
    IMSDK.prototype._onRead = function (message) {
        var web_read_object = JSON.stringify(message.syncReadItems.map(function (item) {
            return {
                id: item.chatId,
                cts: item.stamp,
                sts: item.sts
            };
        }));
        // Log.log('IMSDK::_onRead im receive read sync info:' + web_read_object)
        analytics_1.default.report({
            nm: 'read_im_receive',
            val: {
                'web_read': web_read_object
            }
        });
        eventEmitter_1.default.emit(constant_1.MESSAGE_EVENT.IM_READ, message);
        eventEmitter_1.default.emit('read', message);
    };
    /**
     * 用于处理Read ACK（只需要接收，不需要回复）。发送已读同步的结果
     *
     * @memberof IMSDK
     */
    IMSDK.prototype._onReadACK = function (_a) {
        var msgUuid = _a.msgUuid;
        if (msgUuid && this._readTimeMap[msgUuid]) {
            var valObject = {
                uuid: msgUuid,
                time: Date.now() - this._readTimeMap[msgUuid]
            };
            // Log.log('IMSDK::_onReadACK im send read sync result info:' + JSON.stringify(valObject))
            analytics_1.default.report({
                nm: 'read_im_success',
                val: valObject
            });
            delete this._readTimeMap[msgUuid];
        }
        eventEmitter_1.default.emit(constant_1.MESSAGE_EVENT.IM_READ_ACK, { uuid: msgUuid });
    };
    /**
     * @param message {!IMGroupNotice}
     */
    IMSDK.prototype._onNotice = function (message) {
        eventEmitter_1.default.emit('notice', message);
    };
    IMSDK.prototype._onReciept = function (message) {
        eventEmitter_1.default.emit('receiptResponse', message);
    };
    IMSDK.prototype._onOppositeReadAck = function (message) {
        eventEmitter_1.default.emit('oppositeReadAck', message);
    };
    IMSDK.prototype._onOppsiteRead = function (message) {
        eventEmitter_1.default.emit('oppositeRead', message);
    };
    IMSDK.prototype._onReceiptGroupMessage = function (message) {
        eventEmitter_1.default.emit(constant_1.MESSAGE_EVENT.RECEIPT_GROUP_MESSAGE, message);
    };
    IMSDK.prototype._onReceiptGroupMessageAck = function (message) {
        eventEmitter_1.default.emit(constant_1.MESSAGE_EVENT.RECEIPT_GROUP_MESSAGE_ACK, message);
    };
    IMSDK.prototype._onMessageAddition = function (data) {
        eventEmitter_1.default.emit(constant_1.MESSAGE_EVENT.IM_MESSAGE_ADDITION, data);
    };
    IMSDK.htpconstant = im_constant_1.default;
    IMSDK.Session = im_session_1.default;
    IMSDK.Message = im_message_1.default;
    return IMSDK;
}());
exports.default = IMSDK;


//# sourceURL=webpack://MTDX/./src/core/im/index.ts?